<?php

namespace app\admin\controller;

use app\models\{User as Users, Shoplist};
use think\Db;
use think\Validate;

class User extends Base
{
    public function user()
    {
        $model = new Users();
        $shopmodel = new Shoplist();
        $data = $this->request->get();
        $result = $model->order('id desc');
        if (!empty($data['title'])) {
            $result = $result->where('nickName|mobile', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['shopid'])) {
            $result = $result->where('shopid', $data['shopid']);
        }
        $shoplist = $shopmodel->field('id,title,account')->select();
        $result = $result->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['shopname'] = $shopmodel->where('id', $results['shopid'])->value('title') ?? '';
        }
        return view(null, [
            'shoplist' => $shoplist,
            'list' => $result
        ]);
    }
    public function unshopid_str()
    {
        $account = $this->request->post('account', '');
        $id = $this->request->post('id/d', 0);
        $user = (new Users())->where('id', $id)->find();
        if (empty($user)) {
            return json(['code' => 1, 'data' => [], 'msg' => '用户不存在']);
        }
        if ($user['shopid'] > 0) {
            $res = (new Users())->where('id', $id)->update(['shopid' => 0]);
        } else {
            if (empty($account)) {
                return json(['code' => 1, 'data' => [], 'msg' => '请填写商家账号']);
            }
            $shop = (new Shoplist())->where('account', $account)->find();
            if (empty($shop)) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家账号不存在']);
            }
            $res = (new Users())->where('id', $id)->update(['shopid' => $shop['id']]);
        }
        if ($res) {
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }
}
